package com.ygxsk.carhome.ui.usercenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.arialyy.aria.util.ALog;
import com.blankj.utilcode.BuildConfig;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CleanUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.NotificationUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.tencent.mmkv.MMKV;
import com.tencent.smtt.sdk.QbSdk;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.CarApplication;
import com.ygxsk.carhome.ICallbackResult;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.XXPermissionsDialogDimss;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.SystemConfigEntity;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.svg.GlideCatchUtil;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.MyNotificationUtils;
import com.ygxsk.carhome.utils.ViewUitls;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.functions.Predicate;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @date 2018/1/11 0011
 * @auther itchenqi
 * @description 个人中心---设置界面
 */
public class SettingActivity extends ErrorActivity implements XXPermissionsDialogDimss {

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    private PermissionSetting mSetting;

    /**
     * 标志是否是手动点击更新版本false是刚进入设置界面主动更新控制小红点，true是手动点击了“版本更新”条目，去主动更新版本
     */
    private boolean isClickCheckVersion = false;


    //================================================================================


    /**
     * 标识巡检的内容是否是绑定上
     */
    private boolean isConnected_inspect = false;


    /**
     * 做界面优化的弹窗
     */
    private AlertView mAlertView;

    @BindView(R.id.rl_my_info)
    RelativeLayout rl_my_info;//我的资料

    @BindView(R.id.rl_clean_cache)
    RelativeLayout rl_clean_cache;//清理缓存

    @BindView(R.id.rl_about_me)
    RelativeLayout rl_about_me;

    @BindView(R.id.layoutcheckversion)
    RelativeLayout layoutCheckVersion;//检查新版本

    @BindView(R.id.imageviewupdatedian)
    ImageView imageviewUpdateDian;

    @BindView(R.id.textviewupdatecont)
    TextView textviewUpdateContent;

    @BindView(R.id.layoutsetdetail)
    RelativeLayout layoutSetDetail;//应用设置

    //通知权限检测
    @BindView(R.id.layoutsetnotification)
    RelativeLayout layoutSetNotification;

    //当前系统的版本检测和系统的android版本
    @BindView(R.id.textViewSDKcodeHandler)
    TextView textViewSDKcodeHandler;

    @BindView(R.id.textViewSDKcode)
    TextView textViewSDKcode;

    /**
     * 注销账号的功能
     */
    @BindView(R.id.layoutlogoutcontent)
    RelativeLayout layoutLogOutContent;

    //@BindView(R.id.layoutloginout)
    //TextView layoutloginout;//退出登录的按钮内容。

    /**
     * 提交本地未提交的缓存数据的弹窗,是三者的弹窗内容
     */
    private MaterialDialog materialDialogUpload;


    /**
     * 存放缓存数据内容
     */
    @BindView(R.id.textViewCacheContent)
    TextView textViewCacheContent;

    //是否开通法大大的 展示逻辑
    @BindView(R.id.textviewmysignature)
    TextView textViewMySignature;

    @Override
    public void dialogDimss(MaterialDialog _materialDialog) {

        CommUtils.checkMaterialDialog(_materialDialog);

    }


    //处理该界面的数据内容；
    private static class BetterHandlerSetting extends Handler {

        // ⚠ In Android, Handler classes should be static or leaks might occur.
        private final WeakReference<SettingActivity> mActivityInitialize;

        private BetterHandlerSetting(SettingActivity _settingActivity, Looper looper) {
            super(looper);
            this.mActivityInitialize = new WeakReference<SettingActivity>(_settingActivity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            SettingActivity settingActivity = mActivityInitialize.get();

            if (settingActivity != null) {

                switch (msg.what) {

                    case 22: {

                        if (settingActivity.textViewCacheContent != null) {
                            settingActivity.textViewCacheContent.setText(String.valueOf(msg.obj));
                        }

                        settingActivity.initViews();

                        break;
                    }
                    default:
                        break;
                }

            }

        }
    }

    @OnClick({
            R.id.rl_my_signature,//【我的电子签章认证】
            R.id.rl_my_info,//【我的资料】页面修改头像和昵称
            R.id.rl_push_message,//设置消息推送的界面
            R.id.layoutchangepassword,//密码修改
            R.id.layouthelpcenter,//帮助中心 2023-8-21 11:43:20添加此模块
            R.id.layoutfeedback,//意见反馈
            R.id.rl_clean_cache,//清除缓存
            R.id.layoutcheckversion,//版本更新//R.id.rl_systemerrorlogcat,//服务器报错的系统日志
            R.id.layoutlogoutcontent,//注销账号的功能
            R.id.layoutsetdetail,//应用设置
            R.id.layoutsetnotification,//通知权限检测
            R.id.layoutsetnotificationhandler,//手动打开权限
            R.id.layoutloginout,//退出登录按钮
            R.id.rl_about_me})//关于我们
    public void ClickInSeting(View view) {

        switch (view.getId()) {

            case R.id.layoutsetnotificationhandler: {//手动打开权限设置：

                //检测通知权限没有打开：
                materialDialog = CommUtils.authorityRequest(SettingActivity.this, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_POST_NOTIFICATIONS, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);
                        MyNotificationUtils.requestNotificationListenerPermission(SettingActivity.this);

                    }
                });

                break;
            }

            case R.id.layoutsetnotification: {//判断通知是否可用

                //判断 android11
                CommTools.setNotification(SettingActivity.this, SettingActivity.this, SettingActivity.this, true);

                break;
            }

            case R.id.rl_my_signature: {//验证员工个人的 法大大认证是否开通

//                if (!DoubleClickListener.isFastDoubleClick()) {
//                    ActivityUtils.startActivity(MyInfoActivity.class);
//                }

                //先检测 这个员工个人是否认证法大大
//                gainCheckPermissions();

                //如果个人没有认证法大大，也是弹窗去认证
                //

                gain_check_permissions_open_signature();


                break;
            }

            case R.id.rl_my_info: {

                if (!DoubleClickListener.isFastDoubleClick()) {
                    ActivityUtils.startActivity(MyInfoActivity.class);
                }

                break;
            }

            case R.id.rl_about_me: {//关于我们

                if (!DoubleClickListener.isFastDoubleClick()) {

                    ActivityUtils.startActivity(AboutMeActivity.class);

                }

                break;
            }

            case R.id.rl_push_message: {//设置消息推送的界面

                if (!DoubleClickListener.isFastDoubleClick()) {

                    //直接打开消息设置界面。
                    ActivityUtils.startActivity(PushUmSettingActivity.class);

                }

                break;
            }

            case R.id.layoutchangepassword: {//修改密码

                if (!DoubleClickListener.isFastDoubleClick()) {

                    //暂时不用携带数据
                    ActivityUtils.startActivity(ChangePasswordActivity.class);

                }

                break;
            }

            case R.id.layouthelpcenter: {//帮助中心

                if (!DoubleClickListener.isFastDoubleClick()) {

                    Bundle bundle = new Bundle();
                    bundle.putInt(ExtraKey.EXTRA_WEBVIEW_FLAG, ExtraValue.WEBVIEWFLAG_HELPCENTER);
                    bundle.putString(ExtraKey.EXTRA_CATEGORY_NAME, getString(R.string.set_help_center));
                    bundle.putString(ExtraKey.ISJUMPFROM_HOMETOP_TITLE, getString(R.string.set_help_center));

                    //携带的是固定的地址信息
                    bundle.putString(ExtraKey.EXTRA_WEBVIEW_LOADURL, ApiService.helpcCenterUrlOfficial);

                    ActivityUtils.startActivity(bundle, WebViewNormalActivity.class);

                }

                break;
            }

            case R.id.layoutfeedback: {//意见反馈

                if (!DoubleClickListener.isFastDoubleClick()) {

                    Bundle bundle = new Bundle();
                    bundle.putString(ExtraKey.EXTRA_CATEGORY_NAME, getString(R.string.feedbacktitle));
                    bundle.putString(ExtraKey.ISJUMPFROM_HOMETOP_TITLE, getString(R.string.feedbacktitle));
                    bundle.putString(ExtraKey.EXTRA_WEBVIEW_TITLENAME, getString(R.string.feedbacktitle));
                    bundle.putInt(ExtraKey.EXTRA_WEBVIEW_FLAG, ConstantApi.VALUE_JUMPFROM_SUGGESTIONS_MAINPAGE);
                    ActivityUtils.startActivity(bundle, WebViewNormalActivity.class);

                }

                break;
            }

            case R.id.rl_clean_cache: {//清理缓存

                if (!DoubleClickListener.isFastDoubleClick()) {

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                        if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                                @Override
                                public void doSomeThing() {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    //添加权限功能
                                    AndPermission.with(mActivityInstance)//
                                            .runtime()//
                                            .permission(Permission.READ_EXTERNAL_STORAGE,//
                                                    Permission.WRITE_EXTERNAL_STORAGE)//
                                            .rationale(new RuntimeRationale())//
                                            .onGranted(new Action<List<String>>() {//
                                                @Override
                                                public void onAction(List<String> permissions) {

                                                    method_inside();


                                                }
                                            }).onDenied(new Action<List<String>>() {
                                                @Override
                                                public void onAction(List<String> permissions) {
                                                    //弹出失败弹窗
                                                    if (AndPermission.hasAlwaysDeniedPermission(SettingActivity.this, permissions)) {//
                                                        mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, SettingActivity.this, permissions);//
                                                    }
                                                }
                                            }).start();

                                }
                            });

                        } else {

                            method_inside();

                        }


                    } else {

                        if (!XXPermissions.isGranted(SettingActivity.this, com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {

                                @Override
                                public void doSomeThing() {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    XXPermissions.with(SettingActivity.this)
                                            // 适配分区存储应该这样写
                                            //.permission(Permission.Group.STORAGE)
                                            // 不适配分区存储应该这样写
//                                                        .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                                            .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
//                                            .interceptor(new PermissionInterceptor())
                                            .request(new OnPermissionCallback() {

                                                @Override
                                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                    if (!allGranted) {
                                                        return;
                                                    }

                                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                            PermissionNameConvert.getPermissionString(SettingActivity.this, permissions)));

                                                    method_inside();

                                                }
                                            });

                                }
                            });

                        } else {
                            method_inside();
                        }

                    }

                }


                break;
            }

            case R.id.layoutcheckversion: {//检查新版本


                if (!DoubleClickListener.isFastDoubleClick()) {


                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                        if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                                @Override
                                public void doSomeThing() {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    //检查新版本填充权限
                                    AndPermission.with(mActivityInstance)//
                                            .runtime()//
                                            .permission(Permission.READ_EXTERNAL_STORAGE,//
                                                    Permission.WRITE_EXTERNAL_STORAGE)//
                                            .rationale(new RuntimeRationale())//
                                            .onGranted(new Action<List<String>>() {//

                                                @Override
                                                public void onAction(List<String> permissions) {

                                                    method_inside_clear();

                                                }
                                            }).onDenied(new Action<List<String>>() {
                                                @Override
                                                public void onAction(List<String> permissions) {
                                                    //弹出失败弹窗
                                                    if (AndPermission.hasAlwaysDeniedPermission(SettingActivity.this, permissions)) {//
                                                        mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, SettingActivity.this, permissions);//
                                                    }
                                                }
                                            }).start();

                                }
                            });

                        } else {

                            method_inside_clear();

                        }

                    } else {


                        if (!XXPermissions.isGranted(SettingActivity.this, com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)) {

                            CommUtils.checkMaterialDialog(materialDialog);

                            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {

                                @Override
                                public void doSomeThing() {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    XXPermissions.with(SettingActivity.this)
                                            // 适配分区存储应该这样写
                                            //.permission(Permission.Group.STORAGE)
                                            // 不适配分区存储应该这样写
//                                             .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                                            .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                                            .interceptor(new PermissionInterceptor())
                                            .request(new OnPermissionCallback() {

                                                @Override
                                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                    if (!allGranted) {
                                                        return;
                                                    }

                                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                            PermissionNameConvert.getPermissionString(SettingActivity.this, permissions)));

                                                    method_inside_clear();

                                                }
                                            });

                                }
                            });
                        } else {
                            method_inside_clear();
                        }

                    }

                }

                break;
            }

            case R.id.layoutlogoutcontent: {//注销账号的功能

                if (!DoubleClickListener.isFastDoubleClick()) {
                    //直接的跳转到注销账号的弹窗，就在当前界面上。
                    method_logOutDialog();
                }

                break;
            }

            case R.id.layoutsetdetail: {

                if (!DoubleClickListener.isFastDoubleClick()) {

                    //Launch the application's details settings.
                    //打开系统的权限设置
                    PermissionUtils.launchAppDetailsSettings();

                }

                break;
            }

            case R.id.layoutloginout: {//退出登录按钮

                CommUtils.checkDialog(mAlertView);

                mAlertView = new AlertView(ConstantSign.ALERT_TITLE, //
                        "确定退出此账号？", //
                        "取消", //
                        new String[]{"确定"}, //
                        null, //
                        this, //
                        AlertView.Style.Alert, //
                        new OnItemClickListener() {

                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position != AlertView.CANCELPOSITION) {

                                    if (NetworkUtils.isConnected()) {

                                        method_loginOut();

                                    } else {

                                        CommUtils.setNetwork(mActivityInstance);
                                    }

                                }

                            }
                        });

                mAlertView.setCancelable(true).show();//

                break;
            }

            case R.id.rl_systemerrorlogcat: {//查看系统日志,这个应该是没有，不会走这里

                if (!DoubleClickListener.isFastDoubleClick()) {

                    try {
                        //do


                        //测试代码内容--------------------------------------------------------------------------------------
                    /*if (UtilsBridge.isSDCardEnableByEnvironment()
                            && Utils.getApp().getExternalFilesDir(null) != null)
                        mDefaultDir = Utils.getApp().getExternalFilesDir(null) + File.separator + "log" + File.separator;
                    else {
                        mDefaultDir = Utils.getApp().getFilesDir() + File.separator + "log" + File.separator;
                    }*/

                        //File file = new File(PathUtils.getExternalAppFilesPath() + File.separator + "log" + File.separator);
                        //LogUtils.d("itchen----那么  log 目录==>" + file);
                        //itchen----那么  log 目录==>/storage/emulated/0/Android/data/com.dgj.propertysmart/files/log

                        //获取父目录
                        //File parentFlie = new File(file.getParent());

                        //LogUtils.d("itchen----那么父目录==>" + parentFlie);
                        //itchen----那么父目录==>/storage/emulated/0/Android/data/com.dgj.propertysmart/files
                        //itchen----那么父目录==>/storage/emulated/0/Android/data/com.dgj.propertysmart/files

                        //--------------------------------------------------------------------------------------

                        //File parentFlie = new File(PathUtils.getExternalAppFilesPath() + File.separator);
                        //File parentFlie = new File(PathUtils.getInternalAppFilesPath() + File.separator);
                        File parentFlie = new File(PathUtils.getExternalAppFilesPath() + "/" + "log" + "/");
                        //File parentFlie = new File(PathUtils.getExternalAppFilesPath());
                        //LogUtils.d("itchen----parentFlie---->" + parentFlie);
                        //LogUtils.d("itchen----getInternalAppDataPath---->" + parentFlie);
                        //LogUtils.d("itchen----getInternalAppFilesPath---->" + parentFlie);
                        //itchen----getInternalAppFilesPath---->/data/user/0/com.dgj.propertysmart/files

                        //itchen----getInternalAppDataPath---->/data/user/0/com.dgj.propertysmart
                        //itchen----parentFlie---->/storage/emulated/0/Android/data/com.dgj.propertysmart/files/log
                        //itchen----parentFlie---->/storage/emulated/0/Android/data/com.dgj.propertysmart/files

                        Intent intentOpenSystemLogDir = new Intent(Intent.ACTION_GET_CONTENT);
                        //Intent intentOpenSystemLogDir = new Intent(Intent.ACTION_VIEW);
                        //intentOpenSystemLogDir.addCategory(Intent.CATEGORY_OPENABLE);
                        intentOpenSystemLogDir.addCategory(Intent.CATEGORY_DEFAULT);
                        intentOpenSystemLogDir.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                            //第二个参数要和Mainfest中<provider>内的android:authorities 保持一致
                            //Uri uri = FileProvider.getUriForFile(mActivityInstance, "com.dgj.propertysmart.fileprovider", parentFlie);
                            Uri uri = FileProvider.getUriForFile(mActivityInstance, BuildConfig.LIBRARY_PACKAGE_NAME.concat(".provider"), parentFlie);
                            //intentOpenSystemLogDir.setDataAndType(uri, "application/vnd.android.package-archive");
                            //intentOpenSystemLogDir.setDataAndType(uri, "*/*");
                            //intentOpenSystemLogDir.setDataAndType(uri, "file/*.txt");
                            //intentOpenSystemLogDir.setDataAndType(uri, "*/*");
                            intentOpenSystemLogDir.setDataAndType(uri, "*/*");

                            intentOpenSystemLogDir.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                        } else {
                            //打开指定的文件 apk等
                            //intentOpenSystemLogDir.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                            //intentOpenSystemLogDir.setDataAndType(Uri.fromFile(file), "*/*");
                            //intentOpenSystemLogDir.setDataAndType(Uri.fromFile(parentFlie), "*/*");
                            intentOpenSystemLogDir.setDataAndType(Uri.fromFile(parentFlie), "*/*");
                        }

                        startActivity(intentOpenSystemLogDir);

                    } catch (Exception e) {

                        ToastUtils.showShort(StringUtils.getString(R.string.looksysworkdiary));
                        //catch
                        //LogUtils.e("itchen----->"+ e.getMessage());
                        //LogUtils.e("itchen----->" + e.getLocalizedMessage());

                    }

                }

                break;
            }
            default:
                break;
        }

    }

    //单独的处理退出登陆的点击内容
    /*public void clickLoginOut(View view) {

        //if (!DoubleClickListener.isFastDoubleClick()) {

            CommUtils.checkDialog(mAlertView);

            mAlertView = new AlertView("", //
                    "确定退出此账号？", //
                    "取消", //
                    new String[]{"确定"}, //
                    null, //
                    this, //
                    AlertView.Style.Alert, //
                    new OnItemClickListener() {

                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                if (NetworkUtils.isConnected()) {

                                    method_loginOut();

                                } else {

                                    CommUtils.displayToastShort(SettingActivity.this, ConstantApi.NONET);
                                }

                            }

                        }
                    });

            mAlertView.setCancelable(true).show();//
        //}

    }*/

    private void method_inside_clear() {

        isClickCheckVersion = true;

        if (NetworkUtils.isConnected()) {
            getSystemConfig();
        } else {
            ToastUtils.showShort(ConstantSign.NONET);
        }

    }

    /**
     * 权限的内容
     */
    private void method_inside() {

        //=========================================================================================

        CommUtils.checkDialog(mAlertView);

        mAlertView = new AlertView(ConstantSign.ALERT_TITLE, //
                "确定要清理缓存吗？", //
                "取消", //
                new String[]{"确定"}, //
                null, //
                SettingActivity.this, //
                AlertView.Style.Alert, //
                new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {

                        if (position != AlertView.CANCELPOSITION) {

                            //更新文本内容
                            //清理缓存内容，然后更改缓存字样
                            //GlideCatchUtil.getInstance().clearCacheDiskSelf();//自带的方法删除

                            mCompositeDisposable.add(Observable.just(1, 2, 3, 4, 5, 6)//
                                    .subscribeOn(AndroidSchedulers.mainThread())//
                                    .observeOn(AndroidSchedulers.mainThread())//
                                    .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                                    .subscribe(new Consumer<Integer>() {//
                                        @Override
                                        public void accept(Integer integer) throws Exception {

                                            if (integer == 1) {

                                                //boolean cleanImage = GlideCatchUtil.getInstance().cleanCatchDisk();//手动的方法删除图片缓存
                                                //LogUtils.d("itchen--删除图片缓存="+cleanImage);
                                                GlideCatchUtil.getInstance().cleanCatchDisk();

                                            } else if (integer == 2) {

                                                //boolean cleanApk = GlideCatchUtil.getInstance().cleanCacheApk();//手动删除apk缓存
                                                //LogUtils.d("itchen--删除apk缓存="+cleanApk);
                                                GlideCatchUtil.getInstance().cleanCacheApk();


                                            } else if (integer == 3) {

                                                GlideCatchUtil.getInstance().clearCacheMemory();

                                            } else if (integer == 4) {//最后一步清理Glide内存缓存

                                                //CleanUtils.cleanInternalCache();
                                                //boolean cleanInternalCache =  CleanUtils.cleanInternalCache();

                                                //bug:这行代码不能删；早期原始代码，不能这样直接删除 因为本地有离线缓存 导致离线数据竟然被删了
                                                //FileUtils.delete(PathUtils.getExternalAppFilesPath());

                                                //同时 清理掉 工单拍照的 图片 信息：
                                                //这里只有当 本地没有离线的巡检或者工单数据时候 才可以清理。
//                                                if (((mSession.getInspectPoolAll() != null) && (!mSession.getInspectPoolAll().isEmpty())//
//                                                        || (mSession.getWorkPoolAll()) != null && (!mSession.getWorkPoolAll().isEmpty())//
//                                                        || (mSession.getEquipmentPoolAll() != null) && (!mSession.getEquipmentPoolAll().isEmpty()))) {
//
//                                                    //CommUtils.method_showAlertViewSingle(mActivityInstance, "有离线数据提示", "有离线存储,不能清理图片", false);
//                                                    //LogUtils.d("itchen---->本地有离线的 数据，所以  本地的图片 暂时不能删除缓存。");
//
//                                                    //清理缓存成功提示内容
//                                                    if (CleanUtils.cleanInternalCache()) {
//                                                        ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
//                                                        ToastUtils.showShort("除了图片以外的缓存已清理~");
//                                                    }
//
//                                                    methodUpLoadHasNotLocalData("有离线存储，不能清理图片。是否提交?");
//
//                                                } else {
//
//                                                    //LogUtils.d("itchen---->本地  没有 离线的 数据，所以  本地的图片   可以删除缓存。");
//
//                                                    //给了一个清理缓存图片的入口。
//                                                    //暂时是清理所有图片，文件夹 可以不删除。
//                                                    TaskPicUtils.methodDeleteImageFileInTinyAndEndWithjpg();
//                                                    //LogUtils.d("itchen----->PathUtils.getExternalAppFilesPath()=>" + PathUtils.getExternalAppFilesPath());
//                                                    //itchen----->PathUtils.getExternalAppFilesPath()=>/storage/emulated/0/Android/data/com.dgj.propertysmart/files
//
//                                                    //2022-5-6 暂时将所有的都删掉吧，
//                                                    //2022年6月14日15:41:28  这里有workeroffline是不能清理的;
////                                                    FileUtils.delete(PathUtils.getExternalAppFilesPath() + File.separator + "log");
////                                                    FileUtils.delete(PathUtils.getExternalAppFilesPath() + File.separator + "tbslog");
////                                                    FileUtils.delete(PathUtils.getExternalAppFilesPath() + File.separator + "env");
////                                                    FileUtils.delete(PathUtils.getExternalAppFilesPath() + File.separator + "pgycrash");
////                                                    FileUtils.delete(PathUtils.getExternalAppFilesPath() + File.separator + "stable");
//
//                                                    //其他的不能清理；
//                                                    //重新计算缓存
//                                                }

                                                //清理缓存成功提示内容
                                                if (CleanUtils.cleanInternalCache()) {
                                                    //ToastUtils.make().setGravity(Gravity.CENTER, 0, 0);
                                                    //ToastUtils.showShort("缓存已清理~");
                                                    //做成弹窗的醒目设置：bug 因为华为审核被拒绝，所以做的醒目一些；
                                                    CommUtils.checkDialog(mAlertView);
                                                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.hasclearcache), true);
                                                    mAlertView.show();
                                                }


                                            } else if (integer == 5) {

                                                //是要清理webview的缓存内容

                                                //首先清理webview的缓存内容
                                                QbSdk.clearAllWebViewCache(mActivityInstance, true);

                                                //清理本地的webview的缓存设置
                                                //webViewX5.getSettings().setAppCachePath(PathUtils.getInternalAppCachePath());
                                                //需要清理 PathUtils.getInternalAppCachePath() 的内容，因为webview的设置缓存的目录在里边

                                                //LogUtils.d("itchen---->即将清理路径是-->" + PathUtils.getInternalAppCachePath());
                                                //itchen---->即将清理路径是-->/data/user/0/com.dgj.propertysmart/cache
                                                //itchen---->即将清理路径是-->/data/user/0/com.dgj.propertysmart/cache

                                                //LogUtils.d("itchen---->如果清理cache-CleanUtils.cleanInternalCache()的路径是-->" + Utils.getApp().getCacheDir());
                                                //itchen---->如果清理cache-CleanUtils.cleanInternalCache()的路径是-->/data/user/0/com.dgj.propertysmart/cache

                                                //和CleanUtils.cleanInternalCache()的效果是一样的。
                                                FileUtils.delete(PathUtils.getInternalAppCachePath());

                                            } else if (integer == 6) {

                                                //重新计算缓存数据的大小。
                                                //String cachesize = GlideCatchUtil.getInstance().getCacheSize();
                                                Message message = mHandler.obtainMessage(22);
                                                //这里做个假象，真实的图片不能删，因为可能上传出现 空指针；
                                                message.obj = FileUtils.getSize(PathUtils.getInternalAppCachePath());
                                                //message.obj = FileUtils.getSize(PathUtils.getExternalAppFilesPath());
                                                //GlideCatchUtil.getInstance().getCacheSize();
                                                mHandler.sendMessageDelayed(message, 500);

                                            }
                                        }
                                    }));

                        }
                    }
                });

        mAlertView.setCancelable(true).show();

        //=========================================================================================

    }


    private Session mSession;

    /**
     * 本地离线巡检现有的数据
     */
    private int currentInspectTaskNumber = 0;
    /**
     * 本地的离线的设备保养的数据
     */
    private int currentEquipmentTaskNumber = 0;
    /**
     * 本地的离线的工单池的数量
     */
    private int currentWorkPoolNumber = 0;

    /**
     * 注销账号的弹窗内容
     */
    private MaterialDialog materialDialogLogOut;
    /**
     * 提交确认注销时候的提交进度圈
     */
    private MaterialDialog materialDialogSubmit;

    //该页面的布局处理器；
    private BetterHandlerSetting mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;
        //LogUtils.d("itchen---onCreate");

        mSession = Session.get(this);

//        mSession.setSettingActivity(this);
        mSetting = new PermissionSetting(this);
        //apiRequestSubSonListener = new ApiRequestSubSonListener();

        if (mHandler == null) {
            mHandler = new BetterHandlerSetting(this, Looper.getMainLooper());
        }

        initViews();

        //添加EventBus的监听内容
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }

        //通知栏目弹出权限
        //LogUtils.d("itchen---PhoneUtils.getDeviceId()="+ PhoneUtils.getDeviceId());
        //itchen---PhoneUtils.getDeviceId()=867785030437113
        //LogUtils.d("itchen---DeviceUtils.getAndroidID()="+ DeviceUtils.getAndroidID());
        //itchen---DeviceUtils.getAndroidID()=4385c2b7089fbcd1

        //注册一个下载
        Aria.download(this).register();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)//
                //.titleBar(R.id.toolbarygxskout)
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //LogUtils.d("itchen---onResume");

        //填充文字是否已经开启
        if (textViewSDKcode != null) {

//            Delivery.getInstance().post(new Runnable() {
//                @Override
//                public void run() {
//                    //设置版本号信息
//                    textViewSDKcode.setText();
//                }
//            });

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                boolean isCanAble = NotificationUtils.areNotificationsEnabled();

                if (isCanAble) {
                    Delivery.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            //设置版本号信息
                            textViewSDKcode.setText(getResources().getString(R.string.notification_has_opened));
                        }
                    });

                } else {

                    Delivery.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            //设置版本号信息
                            textViewSDKcode.setText(getResources().getString(R.string.notification_has_not_opened));
                        }
                    });

                }

            } else {

                //如果是大于android13的版本，那么
                boolean isCanAble = XXPermissions.isGranted(SettingActivity.this, com.hjq.permissions.Permission.POST_NOTIFICATIONS);

                if (isCanAble) {
                    Delivery.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            //设置版本号信息
                            textViewSDKcode.setText(getResources().getString(R.string.notification_has_opened));
                        }
                    });

                } else {

                    Delivery.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            //设置版本号信息
                            textViewSDKcode.setText(getResources().getString(R.string.notification_has_not_opened));
                        }
                    });

                }


            }

        }


        mSession = Session.get(this);

        isClickCheckVersion = false;

        //暂时屏蔽掉那个检查版本更新
        getSystemConfig();

        //判断员工是否开通法大大，然后文字显示在 文字后边；
        gain_checkUserFasc();

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mAlertView != null) {
            if (mAlertView.isShowing()) {
                mAlertView.dismiss();
                mAlertView = null;
            }
        }
        //LogUtils.d("itchen--onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();

        //LogUtils.d("itchen--onStop");

        //杀死弹窗
        checkDownLoadDialog();
        checkProgressDialog();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        isClickCheckVersion = false;

        if (mSetting != null) {
            mSetting = null;
        }

        if (mAlertView != null) {
            CommUtils.checkDialog(mAlertView);
            mAlertView = null;
        }

        CommUtils.checkMaterialDialog(materialDialogHasUpdateData);
        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);

        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
            mCompositeDisposable = null;
        }

        if (materialDialogCustomView != null) {
            materialDialogCustomView.dismiss();
            materialDialogCustomView.cancel();
            materialDialogCustomView = null;
        }

        //关闭监听
//        EventBus.getDefault().unregister(this);
        //==========================================================
        //LogUtils.d("itchen--setting-onDestroy");
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_setting;
    }

//    @Override
//    protected void setStatusBar() {
//        //设置单页面的个性化状态栏
//        setStatusBarParent(this.findViewById(R.id.activitysettingoutside));
//    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        toolbarHelper.setTitle(getString(R.string.title_setting));//
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true,//
                R.drawable.backicon,//
                new View.OnClickListener() {//

                    @Override
                    public void onClick(View v) {

                        methodBack();

                    }
                });

        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutRight(false,//
                0, //
                "", //
                null);//

    }

    @Override
    public void onClickNodata(View v) {

        //retain

    }

    @Override
    public void initViews() {

        //获取Glide缓存数据内容
        //String cacheSizeImage = GlideCatchUtil.getInstance().getCacheSize();
        //LogUtils.d("itchen--图片缓存="+cacheSizeImage);
        //String cacheSizedata = GlideCatchUtil.getInstance().getApkCacheSize();
        //LogUtils.d("itchen--apk缓存="+cacheSizedata);

        //2018年04月10日添加访问权限
        /*if (textViewCacheCntent!=null){
            textViewCacheConent.post(new Runnable() {
                @Override
                public void run() {
                    textViewCaceContent.setText(GlideCatchUtil.getInstance().getCacheSize());
                }
            });
        }*/

        //如下是添加权限的内容
        /*AndPermission.with(this)//
                .runtime()//
                .permission(Permission.READ_EXTERNAL_STORAGE,//
                        Permission.WRITE_EXTERNAL_STORAGE)//
                .rationale(new RuntimeRationale())//
                .onGranted(new Action<List<String>>() {//
                    @Override
                    public void onAction(List<String> permissions) {

                        if (textViewCaceContent!=null){
                            textViewCachContent.post(new Runnable() {
                                @Override
                                public void run() {
                                    textViewacheContent.setText(GlideCatchUtil.getInstance().getCacheSize());
                                }
                            });
                        }
                    }
                }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> permissions) {
                //弹出失败弹窗
                if (AndPermission.hasAlwaysDeniedPermission(SettingActivity.this, permissions)) {//
                    mSetting.showSetting(ConstantApi.PERMISSION_NORMAL,SettingActivity.this,permissions);//
                }
            }
        }).start();*/


        //第二种直接读取的：这种不需要权限也可打开，但是不知道其他的国产手机，会不会出现问题。
        if (textViewCacheContent != null) {

            textViewCacheContent.post(new Runnable() {

                @Override
                public void run() {

                    //2019年12月早期代码是getDirSize，但是升级到com.blankj:utilcodex:1.26.0之后就变成了私有的。
                    //textViewCacheContent.setText(FileUtils.getDirSize(PathUtils.getInternalAppCachePath()));

                    //String sizeInternalAppCachePath = FileUtils.getSize(PathUtils.getInternalAppCachePath());
                    //String sizeExternalAppFilesPath = FileUtils.getSize(PathUtils.getExternalAppFilesPath());

                    //LogUtils.d("itchen----sizeInternalAppCachePath--->"+PathUtils.getInternalAppCachePath()+"---缓存大小=>"+sizeInternalAppCachePath);
                    //itchen----sizeInternalAppCachePath--->/data/user/0/com.dgj.propertysmart/cache---缓存大小=>102.939KB
                    //LogUtils.d("itchen----sizeExternalAppFilesPath--->"+PathUtils.getExternalAppFilesPath()+"---缓存大小=>"+sizeExternalAppFilesPath);
                    //itchen----sizeExternalAppFilesPath--->/storage/emulated/0/Android/data/com.dgj.propertysmart/files---缓存大小=>8.359MB

                    //2019年12月10日 变成了统一的获取文件大小。

                    //textViewCacheContent.setText(FileUtils.getSize(PathUtils.getInternalAppCachePath()));

                    //LogUtils.d("itchen---->我取出 计算的缓存路径1==>" + PathUtils.getExternalAppFilesPath());
                    //itchen---->我取出 计算的缓存路径==>/storage/emulated/0/Android/data/com.dgj.propertysmart/files
                    //这里存储的也是一些日志文件，可以手动删除的

                    //LogUtils.d("itchen---->我取出 计算的缓存路径2==>" + PathUtils.getExternalAppDataPath() + File.separator + "tiny");
                    //itchen---->我取出 计算的缓存路径2==>/storage/emulated/0/Android/data/com.dgj.propertysmart/tiny

                    //String filesSize = FileUtils.getSize(PathUtils.getExternalAppFilesPath());

                    textViewCacheContent.setText(FileUtils.getSize(PathUtils.getExternalAppFilesPath()));

                    //textViewCacheContent.setText(GlideCatchUtil.getInstance().getCacheSize());

                }
            });
        }

        //获取android版本
        //获取设备系统版本号
        int getSDKVersionCode = DeviceUtils.getSDKVersionCode();
        String getSDKVersionName = DeviceUtils.getSDKVersionName();

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "current--getSDKVersionCode-->" + getSDKVersionCode);
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "current--getSDKVersionName-->" + getSDKVersionName);

        if (textViewSDKcodeHandler != null) {
            Delivery.getInstance().post(new Runnable() {
                @Override
                public void run() {
                    //设置版本号信息
                    textViewSDKcodeHandler.setText(getResources().getString(R.string.value_sdk) + getSDKVersionCode + "#" + getSDKVersionName);
                }
            });
        }


    }

    @Override
    public void gainDatas() {

        //retain

    }

    @Override
    public void methodBack() {

        isClickCheckVersion = false;

        ActivityUtils.finishActivity(SettingActivity.this);

    }

    private void method_loginOut() {

        HashMap<String, Object> hashMapParameter = new HashMap<>();
        hashMapParameter.put(Parameterkey.key, Parameterkey.null_post);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GOTOEXITVUE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.goToExitVueUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(hashMapParameter);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)//
                .goToExitVue(RequestBody.create(JSON.toJSONString(hashMapParameter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>(ConstantApi.IS_ACTIVITY_ITSELF, SettingActivity.this) {
                    @Override
                    public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity _activity, String statusCode, String message) {
                        super.onErrorServerNotSuccessDataResponse(method, isToastToUser, _activity, statusCode, message);

                        ToastUtils.showShort(message);

                    }
                }))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {

                        //------------------------------------------------------------------------------
//                        //退出之前上传一些退出登录的记录
//                        HashMap<String, Object> hashMapParameterLocal = new HashMap<>();
//                        hashMapParameterLocal.put("communityName", mSession.getShopInfoOrCommunityName());
//                        hashMapParameterLocal.put("customerId", mSession.getCustomerId());
//                        hashMapParameterLocal.put("customerInfoId", mSession.getCustomerInfoId());
//                        hashMapParameterLocal.put("trueName", mSession.getTrueName());
//                        hashMapParameterLocal.put("loginName", mSession.getLoginName());
//                        hashMapParameterLocal.put("phone", mSession.getUserPhone());
//                        hashMapParameterLocal.put("userToken", mSession.getToken());
//                        hashMapParameterLocal.put("loginouttimecustom", TimeUtils.getNowString());
//
//                        new ApiRequestSubListener<>(ConstantApi.IS_ACTIVITY_ITSELF, SettingActivity.this) {
//                            @Override
//                            public void addLogInApiRequestListener(Context _context, String _interfaceAddress, String _requestMethod, HashMap<String, Object> _requestParamObject, String _errorMessageMy) {
//                                super.addLogInApiRequestListener(_context, _interfaceAddress, _requestMethod, _requestParamObject, _errorMessageMy);
//                            }
//                        }.addLogInApiRequestListener(//
//                                mActivityInstance,//
//                                addLogUpLoadInfo.getUrlPath(),//
//                                addLogUpLoadInfo.getRequestMethod(),
//                                addLogUpLoadInfo.getHashMapParameter(),//
//                                "logout success");//
                        //------------------------------------------------------------------------------
                        ///LogUtils.d("itchen--->退出登录--response.succeed---->" + response.succeed());

                        //退出登录的处理逻辑
                        //这一块貌似完全和20401相同=========================================================
                        CommUtils.loginOutClearData(mSession, MMKV.defaultMMKV().decodeString(ConstantSign.P_INPUTNAMELASTTIME));

                        //------------------------------------------------------------------------
                        //2022-11-25 21:17:08 添加退出登录之后删除本地留存的记录小区数据的数据库信息
//                        CommunityDaoManager.getInstance().deleteAllCommunityEntryInfoBean();
                        //------------------------------------------------------------------------
                        ToastUtils.showShort(StringUtils.getString(R.string.logoutexit));

                        Bundle bundle = new Bundle();
                        bundle.putInt(ExtraKey.EXTRA_REQUEST_20401, ExtraValue.RESPONSE_20401);
                        //跳转到登录界面去重新登录。
                        //这个也要走20401用户信息失效的逻辑
                        ActivityUtils.startActivity(bundle, LoginCarActivity.class);

                        //可能要杀死掉 HomeMainActivity
                    }

                    //自定义

                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException e) {
                        //请求失败的处理

                    }
                });

    }

    //检查员工是否开通过法大大，如果没有开通，就弹窗开通，如果开通了，就展示文字 是未开通
    private void gain_checkUserFasc() {

        if (NetworkUtils.isConnected()) {

            HashMap<String, Object> map = new HashMap<>();
//            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//                map.put(Parameterkey.signTaskId, _fileSignatureAgreement.getSignTaskId());//电子签章系统签署任务ID,优先使用签署任务ID
//                map.put(Parameterkey.informationId, _fileSignatureAgreement.getInformationId());//车辆档案ID

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_CHECKUSERFASC_URL);//请求数字标识
            addLogUpLoadInfo.setUrlPath(ApiService.checkUserFasc_url);//url地址
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
            addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .checkUserFasc(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<Boolean>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

//                            CommUtils.checkMaterialDialog(materialDialog);

                            //{"data":"","message":"无更多数据","code":"29999"}
                            //{"data":"","message":"签署任务状态不是填写完成，不允许定稿","code":"29999"}

                            //这里要不要给提示？无更多数据
                            if (!TextUtils.equals(serverCode, ConstantSign.RESPONSE_STRING_29999)) {

                                if (!TextUtils.isEmpty(serverMessage)) {
                                    ToastUtils.showShort(serverMessage);
                                }

                            } else {

                                CommUtils.checkDialog(mAlertView);
                                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, serverMessage, true);
                                mAlertView.show();

                            }

                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {
//                            method_create_materialDialog(ConstantSign.TIPS_LOADING);
                        }
                    }).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean booleanValue) throws Throwable {

//                            CommUtils.checkMaterialDialog(materialDialog);
//                            if (!TextUtils.isEmpty(stringValue)) {
                            //2023-10-27 15:32 链接是要跳转吗？
//                            }

                            if (booleanValue) {
                                CommUtils.setText(textViewMySignature, getString(R.string.bracket_left_small) + getString(R.string.user_check_signatrue_auth) + getString(R.string.bracket_right_small));
                            } else {
                                CommUtils.setText(textViewMySignature, getString(R.string.bracket_left_small) + getString(R.string.user_check_signatrue_noauth) + getString(R.string.bracket_right_small));
                            }

                            //电子合同发起成功
//                          PopTip.show(getResources().getString(R.string.signature_send_success)).iconSuccess();

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {
//                            CommUtils.checkMaterialDialog(materialDialog);
                            //页面报错；给提示
                            if (apiException != null) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }

                        }
                    });

        } else {

            ToastUtils.showShort(StringUtils.getString(R.string.http_exception_network));

        }

    }

    private void getSystemConfig() {

        //String requestUrl = Constants.getInstance().getSystemConfig();
        //Request<JSONObject> request = NoHttp.createJsonObjectRequest(requestUrl, RequestMethod.POST);
        //startRequest(ConstantApi.WHAT_SYSTEMCONFIG, request, httpListener, true, false);

        HashMap<String, Object> hashMapParameter = new HashMap<>();
        //hashMap.put(Parameterkey.key, "getConfigUrl为了获取更新");
        hashMapParameter.put("", "");

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_SETTINGACTIVITY_UPDATEAPK);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getConfigUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(hashMapParameter);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getConfig(RequestBody.create(JSON.toJSONString(hashMapParameter, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<SystemConfigEntity>>(ConstantApi.IS_ACTIVITY_ITSELF, SettingActivity.this) {
                    @Override
                    public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity _activity, String statusCode, String message) {
                        super.onErrorServerNotSuccessDataResponse(method, isToastToUser, _activity, statusCode, message);
                    }
                }))
                .flatMap(new Function<ArrayList<SystemConfigEntity>, ObservableSource<SystemConfigEntity>>() {
                    @Override
                    public ObservableSource<SystemConfigEntity> apply(ArrayList<SystemConfigEntity> systemConfigEntities) throws Exception {
                        return Observable.fromIterable(systemConfigEntities);
                    }
                })
                .filter(new Predicate<SystemConfigEntity>() {
                    @Override
                    public boolean test(SystemConfigEntity systemConfigEntity) throws Exception {
                        return TextUtils.equals(systemConfigEntity.getKey(), ConstantSign.APP_UPDATE_ANDROID_DOWNLOAD_URL);
                    }
                }).flatMap(new Function<SystemConfigEntity, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(SystemConfigEntity systemConfigEntity) throws Throwable {

//                        LogUtils.d("itchen-rxjava-下载地址是：" + systemConfigEntity.getValue());
                        //itchen--下载地址是：http://222.222.17.184:19181/resource/app/apk/20220911083202042/管家物业59.apk

                        if (systemConfigEntity != null) {

                            if (!TextUtils.isEmpty(systemConfigEntity.getValue())) {

                                // : 2023-07-10 14:51 升级该APP
//                                //可能连续更新多个版本，每次都保存最新包,设置一遍内存地址：
                                mSession.setDownloadurlCurrent(systemConfigEntity.getValue());

                            } else {
                                //添加日志上传 是空值
                            }
                        }

                        return Observable.just(1, 2);
                    }
                })
                .subscribe(new Consumer<Integer>() {

                    @Override
                    public void accept(Integer integerUpstreamPull) throws Exception {//如果发现一个匹配条件的，那么

                        if (integerUpstreamPull == 1) {//

                            //二者比较值，都不能为空,解析线上的版本号大于本地目前安装的版本号，那么提示更新
                            if (CommUtils.getServiceVersionCode(mSession) > AppUtils.getAppVersionCode()) {

                                if (isClickCheckVersion) {

                                    //2019/1/27 检查新版本是否已经下载完全
                                    final File apkFile = new File(PathUtils.getExternalAppCachePath() + File.separator +//
                                            mSession.getDownloadurlCurrent().substring(mSession.getDownloadurlCurrent().lastIndexOf("/") + 1));

                                    //boolean isFileExists = FileUtils.isFileExists(apkFile);
                                    //LogUtils.d("itchen----->文件："+apkFile+"是否存在="+isFileExists);

                                    if (FileUtils.isFileExists(apkFile)) {

                                        if (CommUtils.getUninatllApkInfo(Utils.getApp(), apkFile.getAbsolutePath())) {
                                            AppUtils.installApp(apkFile.getAbsolutePath());
                                        } else {
                                            //如果已存在的安装包不完整那么也直接弹窗提示
                                            showDownLoadDialog(mSession.getDownloadurlCurrent());
                                        }

                                    } else {
                                        showDownLoadDialog(mSession.getDownloadurlCurrent());
                                    }

                                }

                                //通用红点文字逻辑-展示
                                layoutCheckVersion.post(new Runnable() {
                                    @Override
                                    public void run() {

                                        CommUtils.setViewVisible(imageviewUpdateDian);
                                        CommUtils.setViewVisible(textviewUpdateContent);
                                        textviewUpdateContent.setText(R.string.click_update_apk);

                                    }
                                });

                            } else {

                                //LogUtils.d("itchen---发现版本号相同--");

                                if (isClickCheckVersion) {

                                    CommUtils.checkDialog(mAlertView);
                                    mAlertView = CommUtils.method_showAlertView(SettingActivity.this, getString(R.string.is_new_apk), null);
                                    mAlertView.setCancelable(true).show();

                                }

                                //通用红点文字逻辑-隐藏
                                CommUtils.setViewGone(imageviewUpdateDian);
                                CommUtils.setViewGone(textviewUpdateContent);
                                textviewUpdateContent.setText("");

                            }

                        } else if (integerUpstreamPull == 2) {
                            isClickCheckVersion = false;
                        }

                    }

                    //自定义

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        //
                    }
                });

    }

    /**
     * 提示有apk更新
     */
    private MaterialDialog materialDialogHasUpdateData;

    private MaterialDialog materialDialogDownLoadProgress;

    //该下载apk任务的任务id值内容；
    private long taskDownLoadApkId;

    /**
     * 下载服务传递过来的进度
     */
    private final ICallbackResult callbackResult = new ICallbackResult() {

        @Override
        public void OnBackResult(final int currentResult) {

            if (currentResult != ConstantApi.APK_DOWNLOADFAIL_FLAG) {

                if (materialDialogDownLoadProgress != null) {

                    //final MaterialDialog curdialog = (MaterialDialog) materialDialogDownLoadProgress;

//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//
//                            curdialog.incrementProgress(1);//增加量1
//                            curdialog.setProgress(currentResult);//设置进度
//
//                        }
//                    }).start();

                    try {

                        //LogUtils.d(ConstantApi.LOGCAT_NOMAL + "更新-首页-materialDialogProgress-进度->" + currentResult);
                        //Thread-9488, com.dgj.propertysmart.ui.home.HomeMainActivity$1$1.run(HomeMainActivity.java:421)
                        //itchen->更新-首页-materialDialogProgress-进度->100
                        materialDialogDownLoadProgress.incrementProgress(1);//每次增加量1
                        materialDialogDownLoadProgress.setProgress(currentResult);//设置进度

                    } catch (Exception e) {
//                        if (!ObjectUtils.isEmpty(e)) {
////                            LogUtils.d(ConstantApi.LOGCAT_NOMAL + "更新-首页-materialDialogProgress-进度-有异常->" + e.getMessage());
//                        }
                        e.printStackTrace();
                    }


                    materialDialogDownLoadProgress.setOnShowListener(new DialogInterface.OnShowListener() {//更新进度
                        @Override
                        public void onShow(DialogInterface dialoginterface) {
                            //更新进度内容
                            final MaterialDialog curdialog = (MaterialDialog) dialoginterface;

                            if (curdialog.getCurrentProgress() != curdialog.getMaxProgress()) {

                                if (!SettingActivity.this.isFinishing()) {//如果界面没有被杀死

                                    if (curdialog.isCancelled()) {
                                        return;
                                    }
                                }
                            }
                        }
                    });
                } else {
                    //-----------------------------------------------------------------
                    //弹窗没有弹出，那么也是无法下载的，需要杀掉服务
//                    if (binderInterface != null) {
//                        //这里目的是为了关闭服务；
//                        binderInterface.callCancel();
//                    } else {
////                        LogUtils.d(ConstantApi.LOGCAT_NOMAL + "binderInterface值是空值");
//                    }

                    //解绑下载的服务模块，同时关闭服务
//                    ServiceUtils.unbindService(conn);
                    //-----------------------------------------------------------------
                }

            } else {
                try {
                    //do

//                    LogUtils.d("itchen--即将执行-APK_DOWNLOADFAIL_FLAG--解除服务断开，关闭弹窗，杀死服务的工作");

                    //2022-11-15 09:27:09 关闭弹窗，消除掉所有可能有得内存泄露问题
                    if (materialDialogDownLoadProgress != null) {
                        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);
                    }

                    //解绑下载的服务模块，同时关闭服务
//                    if (conn != null) {
////                        LogUtils.d("itchen--即将执行-解绑下载的服务unbindService");
//                        SettingActivity.this.unbindService(conn);
//                        //报错java.lang.IllegalArgumentException: Service not registered: com.dgj.propertysmart.ui.home.HomeMainActivity$MyConnHome@be183e7
//                    }

//                    if (ServiceUtils.isServiceRunning(UpdateService.class)) {
//                        if (binderInterface != null) {
//                            //这里目的是为了关闭服务；
//                            binderInterface.callCancel();
//                        } else {
////                            LogUtils.d(ConstantApi.LOGCAT_NOMAL + "binderInterface值是空值");
//                        }
//                    } else {
////                        LogUtils.d(ConstantApi.LOGCAT_NOMAL + "ServiceUtils.isServiceRunning下载apk的服务已经停止了");
//                    }
                } catch (Exception e) {
                    //catch

//                    if (!ObjectUtils.isEmpty(e)) {
//                        LogUtils.d(ConstantApi.LOGCAT_NOMAL + "下载失败的报错日志=>" + e.getLocalizedMessage());
//                    }

                    e.printStackTrace();

                } finally {
//                    LogUtils.d(ConstantApi.LOGCAT_NOMAL + "必然执行了=>materialDialogProgress再检查关闭一次");
                    if (materialDialogDownLoadProgress != null) {
                        CommUtils.checkMaterialDialog(materialDialogDownLoadProgress);
                    }
                }

            }


        }
    };

    private void checkProgressDialog() {
        if (materialDialogDownLoadProgress != null && materialDialogDownLoadProgress.isShowing()) {
            materialDialogDownLoadProgress.dismiss();
        }
    }

    private void showProgressDialog() {

        //关闭上一个
        checkDownLoadDialog();
        checkProgressDialog();

        if (ActivityUtils.isActivityAlive(SettingActivity.this)) {

            materialDialogDownLoadProgress = new MaterialDialog.Builder(SettingActivity.this)
                    .title(AppUtils.getAppName())
                    .content(R.string.downloadingwait)
                    .contentGravity(GravityEnum.CENTER)
                    .progress(false, 100, true)//itchen自己更改 false水平进度条
                    .positiveText(R.string.backgrounddown)//右侧下载
                    .positiveColor(ContextCompat.getColor(Utils.getApp(), R.color.red_normal))
                    .negativeText(R.string.downloadingcancel)//左侧取消
                    .negativeColor(ContextCompat.getColor(Utils.getApp(), R.color.colormobutton))
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {

                            dialog.dismiss();//取消弹窗，取消下载，取消发送进度内容

                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {

                            //触发取消下载。
                            //杀死服务和服务内发送下载的方法
                            //binderInterface.callCancel();

                            //调用下载器的 取消
                            if (Aria.download(SettingActivity.this).load(taskDownLoadApkId).isRunning()) {
                                Aria.download(SettingActivity.this).load(taskDownLoadApkId).cancel();
                            }

                        }
                    }).canceledOnTouchOutside(false)//
                    .show();//

            //这个事件可以不做
               /*.showListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialog) {
                    }
                })*/

            //先创建，然后更新
            //2019/1/27 不修改标题字号,显示为默认的
            materialDialogDownLoadProgress.getTitleView().setTextSize(16);
            //materialDialogProgress.getProgressBar().setAlpha(ContextCompat.getColor(Dutils.getApp(),R.color.colormobutton));
            materialDialogDownLoadProgress.getProgressBar().setAlpha(1);

            materialDialogDownLoadProgress.getActionButton(DialogAction.POSITIVE).setTextSize(15);
            materialDialogDownLoadProgress.getActionButton(DialogAction.NEGATIVE).setTextSize(15);
        }

    }


    private void checkDownLoadDialog() {
        if (materialDialogHasUpdateData != null) {
            materialDialogHasUpdateData.cancel();
        }
    }

    private void showDownLoadDialog(final String _downLoadUrlCurrent) {

        //点击边缘不可更改。要不要区分？强制更新、不强制更新。

        checkDownLoadDialog();

        if (ActivityUtils.isActivityAlive(SettingActivity.this)) {

            materialDialogHasUpdateData = new MaterialDialog.Builder(SettingActivity.this)
                    .title(R.string.updateinfotitle)
                    .titleColor(ContextCompat.getColor(Utils.getApp(), R.color.dark))
                    .content(StringUtils.getString(R.string.updateappinfo))
                    .contentColor(ContextCompat.getColor(Utils.getApp(), R.color.dark))
                    .positiveText(R.string.updateformserver)//右侧下载
                    .positiveColor(ContextCompat.getColor(Utils.getApp(), R.color.red_normal))
                    .negativeText(R.string.updatebuttoncancel)//左侧取消
                    .negativeColor(ContextCompat.getColor(Utils.getApp(), R.color.colormobutton))
                    .neutralText(R.string.updateforlooker)//
                    .neutralColor(ContextCompat.getColor(Utils.getApp(), R.color.colormobutton))
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {//静默下载

                            //CommTools.goToMarket(mActivityInstance, AppUtils.getAppPackageName());


                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                if (!AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)) {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            //2018年06月05日发现这里添加SD卡的存储权限内容
                                            AndPermission.with(SettingActivity.this)//
                                                    .runtime()//
                                                    .permission(Permission.READ_EXTERNAL_STORAGE,//
                                                            Permission.WRITE_EXTERNAL_STORAGE)//
                                                    .rationale(new RuntimeRationale())//
                                                    .onGranted(new Action<List<String>>() {//
                                                        @Override
                                                        public void onAction(List<String> permissions) {

                                                            method_inside_download(_downLoadUrlCurrent);

                                                        }
                                                    }).onDenied(new Action<List<String>>() {
                                                        @Override
                                                        public void onAction(List<String> permissions) {
                                                            //弹出失败弹窗
                                                            if (AndPermission.hasAlwaysDeniedPermission(SettingActivity.this, permissions)) {//
                                                                mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, SettingActivity.this, permissions);//
                                                            }
                                                        }
                                                    }).start();

                                        }
                                    });


                                } else {

                                    method_inside_download(_downLoadUrlCurrent);

                                }

                            } else {

                                if (!XXPermissions.isGranted(SettingActivity.this, com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)) {

                                    CommUtils.checkMaterialDialog(materialDialog);

                                    materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {

                                        @Override
                                        public void doSomeThing() {

                                            CommUtils.checkMaterialDialog(materialDialog);

                                            XXPermissions.with(SettingActivity.this)
                                                    // 适配分区存储应该这样写
                                                    //.permission(Permission.Group.STORAGE)
                                                    // 不适配分区存储应该这样写
//                                                  .permission(com.hjq.permissions.Permission.)//
                                                    .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
//                                                    .interceptor(new PermissionInterceptor())
                                                    .request(new OnPermissionCallback() {

                                                        @Override
                                                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                            if (!allGranted) {
                                                                return;
                                                            }

                                                            Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                    PermissionNameConvert.getPermissionString(SettingActivity.this, permissions)));

                                                            method_inside_download(_downLoadUrlCurrent);

                                                        }
                                                    });

                                        }
                                    });

                                } else {
                                    method_inside_download(_downLoadUrlCurrent);
                                }

                            }
                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {

                            //取消的
                            dialog.dismiss();

                        }
                    }).onNeutral(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            //LogUtils.d("itchen--取消按钮");
                            mSession.setQuitUpdate(true);
                            //直接启用浏览器下载
                            CommUtils.method_inside_download(_downLoadUrlCurrent, SettingActivity.this);
                            dialog.dismiss();
                        }
                    }).dismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {

                            mSession.setQuitUpdate(true);
                            //LogUtils.d("itchen触发取消视图的事件dismissListener");
                        }
                    }).canceledOnTouchOutside(true).show();//这个可以随时获取就放开点击消失

            //2019/1/27 去掉设置顶部标题
            //materialDialog.getTitleView().setTextSize(13);
            materialDialogHasUpdateData.getTitleView().setTextSize(15);
            materialDialogHasUpdateData.getActionButton(DialogAction.POSITIVE).setTextSize(15);
            //materialDialogUpdate.getActionButton(DialogAction.NEGATIVE).setTextSize(15);

        }
    }

    /**
     * 下载地址
     *
     * @param _downLoadUrlCurrent
     */
    private void method_inside_download(String _downLoadUrlCurrent) {

//        //LogUtils.d("itchen--确定按钮");
//        mSession.setQuitUpdate(true);
//
//        //2019年12月11日 这段代码暂时不用。
//        Intent updateIntent = new Intent();
//        updateIntent.setClass(SettingActivity.this, UpdateService.class);
//        updateIntent.putExtra("app_name", AppUtils.getAppName());
//        updateIntent.putExtra("url", _downLoadUrlCurrent);
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(updateIntent);
//        } else {
//            startService(updateIntent);
//        }
//
//        //将来如果这一块有问题直接屏蔽即可
        showProgressDialog();

        //String filePath = PathUtils.getExternalAppCachePath() + File.separator + ConstantSign.DOWNAPP + File.separator+(_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
//        String filePath = PathUtils.getExternalAppFilesPath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
        //String filePath = PathUtils.getExternalAppCachePath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载存放路径地址-->" + CarApplication.getInstance().getApkDownLoadPath(_downLoadUrlCurrent));
        //itchen-->下载地址-->/data/user/0/com.ygxsk.integrated/cache/ccce9ab2828d449f93b5ce3754a05e71.apk

        //使用第三方下载
        taskDownLoadApkId = Aria.download(this)
                .load(_downLoadUrlCurrent)
                .setFilePath(CarApplication.getInstance().getApkDownLoadPath(_downLoadUrlCurrent)) //设置文件保存的完整路径
                .create();   //启动下载


    }


    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {

//        if(task.getKey().eques(task.getKey())){
//        ....
//            可以通过url判断是否是指定任务的回调
//        }
        int p = task.getPercent();  //任务进度百分比
//        String speed = task.getConvertSpeed();  //转换单位后的下载速度，单位转换需要在配置文件中打开
//        String speed1 = String.valueOf(task.getSpeed()); //原始byte长度速度
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL+"下载进度是-->"+speed);
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载进度是-->" + p);

        if (callbackResult != null) {
            callbackResult.OnBackResult(p);
        }

    }


    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        //下载完毕
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载完毕；");
        checkDownLoadDialog();
        checkProgressDialog();

        //String filePath = PathUtils.getExternalAppCachePath() + File.separator + (_downLoadUrlCurrent.substring(_downLoadUrlCurrent.lastIndexOf("/") + 1));
//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "下载完毕后的地址-->" + task.getFilePath());
        //itchen-->下载完毕后的地址-->/storage/emulated/0/Android/data/com.ygxsk.integrated/cache/ea72151429fb4dc0b802ff026fadb22a.apk


        //直接启用安装
        if (!TextUtils.isEmpty(task.getFilePath())) {
            if (CommUtils.getUninatllApkInfo(SettingActivity.this, task.getFilePath())) {
                AppUtils.installApp(task.getFilePath());
            }
        }

    }

    @Download.onTaskCancel
    void taskCancel(DownloadTask task) {

        //LogUtils.d(ConstantSign.LOGCAT_NOMAL+"---->下载取消---");

        //mAdapter.updateState(task.getEntity());
        //判断这个任务在运行的状态中，那么，就直接停止它；
//        if (Aria.download(SettingActivity.this).load(taskDownLoadApkId).isRunning()){
//            Aria.download(SettingActivity.this).load(taskDownLoadApkId).stop();
//        }

        //直接关闭 下载弹窗；
        //立即关闭弹窗的
        checkDownLoadDialog();
        checkProgressDialog();

        ToastUtils.showLong(R.string.downlaodappcancel);

    }

    /**
     * @param e 异常信息
     */
    @Download.onTaskFail
    void taskFail(DownloadTask task, Exception e) {

        //立即关闭弹窗的
        checkDownLoadDialog();
        checkProgressDialog();

        //ALog.d(TAG, ALog.getExceptionString(e));
        //下载任务失败
        //下载失败
        if (!TextUtils.isEmpty(ALog.getExceptionString(e))) {
            ToastUtils.showShort(ALog.getExceptionString(e));
//            LogUtils.d(ConstantSign.LOGCAT_NOMAL+"---->下载报错--->" + ALog.getExceptionString(e));

            //提示下载失败：
            ToastUtils.showShort(ALog.getExceptionString(e));
        }

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThreadEventInspectCloseDialogInSetting(EvnetBusInspectMainCloseDialog evnetBusInspectMainCloseDialog) {
//
//        if (evnetBusInspectMainCloseDialog != null) {
//
//            if (evnetBusInspectMainCloseDialog.getMessage() == ConstantApi.EVENTBUS_FROM_CLOSE_DIALOG_TO_SETTINGACITIVITY_INSPECTTASK_UPLOAD) {
//
//                //LogUtils.d("itchen----->收到了--仅仅是【设置界面 巡检任务 提交弹窗】关闭 消息内容  onEventMainThreadEventInspectCloseDialogInSetting ");
//
//                //可能是从 巡检任务的 service 之中发送过来的。
//                //1关闭弹窗内容: 因为是一个for循环，只能在所有的循环和提交提交完毕之后才能 停止转圈。
//                /*if (ActivityUtils.isActivityAlive(SettingActivity.this)) {
//                    CommUtils.checkMaterialDialog(materialDialogUpload);
//                }*/
//
//                CommUtils.hasNoDataInDaoDoSomeThing(mSession, new AfterListenerQueryDaoSub() {
//                    @Override
//                    public void doSomethingNoData() {
//                        super.doSomethingNoData();
//                        //如果本地没有一个 离线数据那么。
//                        if (ActivityUtils.isActivityAlive(SettingActivity.this)) {
//                            CommUtils.checkMaterialDialog(materialDialogUpload);
//                        }
//                    }
//                });
//
//            }
//        }
//    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThreadEventWorkPoolCloseDialogInSetting(EvnetBusWorkPoolCloseDialog evnetBusWorkPoolCloseDialog) {
//
//        if (evnetBusWorkPoolCloseDialog != null) {
//
//            if (evnetBusWorkPoolCloseDialog.getMessage() == ConstantApi.EVENTBUS_FROM_CLOSE_DIALOG_TO_SETTINGACITIVITY_WORKPOOL_UPLOAD) {
//
//                //LogUtils.d("itchen----->收到了--仅仅是【设置界面 工单池任务 提交弹窗】关闭 提交弹窗的消息内容  onEventMainThreadEventWorkPoolCloseDialogInSetting ");
//
//                //1关闭弹窗内容: 因为是一个for循环，只能在所有的循环和提交提交完毕之后才能 停止转圈。
//                /*if (ActivityUtils.isActivityAlive(SettingActivity.this)) {
//                    CommUtils.checkMaterialDialog(materialDialogUpload);
//                }*/
//
//                CommUtils.hasNoDataInDaoDoSomeThing(mSession, new AfterListenerQueryDaoSub() {
//                    @Override
//                    public void doSomethingNoData() {
//                        super.doSomethingNoData();
//                        //如果本地没有一个 离线数据那么。
//                        if (ActivityUtils.isActivityAlive(SettingActivity.this)) {
//                            CommUtils.checkMaterialDialog(materialDialogUpload);
//                        }
//                    }
//                });
//
//            }
//        }
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThreadEventInspectEquipmentWorkNumber(EventBusToSettingactivityUpdateDialogNumber toUpdateDialogNumber) {
//
//        //如果是三个消息之中的任意一个那么都要刷新这个
//        if (toUpdateDialogNumber != null) {
//
//            if (toUpdateDialogNumber.getMessage() == ConstantApi.EVENTBUS_MESSAGE_FROM_ININSPECTTASKSERVICE_SURPLUSNUMBER) {
//
//                //LogUtils.d("itchen---收到了eventbus消息---sendSurPlusNumberInDao--【本地离线巡检工单剩余】==>" + toUpdateDialogNumber.getSurPlusNumber());
//
//                methodsendSurPlusNumberInDao_inspect(toUpdateDialogNumber.getSurPlusNumber());
//
//            } else if (toUpdateDialogNumber.getMessage() == ConstantApi.EVENTBUS_MESSAGE_FROM_INEQUIPMENTSERVICE_SURPLUSNUMBER) {
//
//                //LogUtils.d("itchen---收到了eventbus消息---sendSurPlusNumberInDao--【本地离线设备保养剩余】==>" + toUpdateDialogNumber.getSurPlusNumber());
//
//                methodsendSurPlusNumberInDao_equipment(toUpdateDialogNumber.getSurPlusNumber());
//
//            } else if (toUpdateDialogNumber.getMessage() == ConstantApi.EVENTBUS_MESSAGE_FROM_INWORKPOOLSERVICE_SURPLUSNUMBER) {
//
//                //LogUtils.d("itchen---收到了eventbus消息---sendSurPlusNumberInDao--【本地离线 工单池 剩余】==>" + toUpdateDialogNumber.getSurPlusNumber());
//
//                methodsendSurPlusNumberInDao_workpool(toUpdateDialogNumber.getSurPlusNumber());
//
//            }
//
//        }
//
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThreadEventEquipmentTaskCloseDialogInSetting(EvnetBusEquipmentMainCloseDialog evnetBusEquipmentMainCloseDialog) {
//
//        if (evnetBusEquipmentMainCloseDialog != null) {
//
//            if (evnetBusEquipmentMainCloseDialog.getMessage() == ConstantApi.EVENTBUS_FROM_CLOSE_DIALOG_TO_SETTINGACITIVITY_EQUIPMENT_UPLOAD) {
//
//                //LogUtils.d("itchen----->收到了--仅仅是【设置界面 设备保养任务 提交弹窗】关闭 提交弹窗的消息内容  onEventMainThreadEventEquipmentTaskCloseDialogInSetting ");
//
//                //1关闭弹窗内容: 因为是一个for循环，只能在所有的循环和提交提交完毕之后才能 停止转圈。
//                /*if (ActivityUtils.isActivityAlive(SettingActivity.this)) {
//                    CommUtils.checkMaterialDialog(materialDialogUpload);
//                }*/
//                CommUtils.hasNoDataInDaoDoSomeThing(mSession, new AfterListenerQueryDaoSub() {
//                    @Override
//                    public void doSomethingNoData() {
//                        super.doSomethingNoData();
//                        //如果本地没有一个 离线数据那么。
//                        if (ActivityUtils.isActivityAlive(SettingActivity.this)) {
//                            CommUtils.checkMaterialDialog(materialDialogUpload);
//                        }
//                    }
//                });
//
//            }
//
//        }
//
//    }

    //给2秒的进度圈圈时间时间，做提交的进度检查:这种只适合少量几条数据。
                                            /*mCompositeDisposable.add(Observable.timer(2000, TimeUnit.MILLISECONDS)//
                                                    .subscribeOn(AndroidSchedulers.mainThread())//
                                                    .observeOn(AndroidSchedulers.mainThread())//
                                                    .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                                                    .subscribe(new Consumer<Long>() {
                                                        @Override
                                                        public void accept(Long aLong) throws Exception {

                                                            CommUtils.checkMaterialDialog(materialDialogUpload);

                                                            CommUtils.displayToastShortCenter("提交完毕~");

                                                        }
                                                    }));*/

    /**
     * 注销账号的功能
     * 2022年1月11日10:14:59 添加为了应用市场能审核通过才改造。
     */
    private void method_logOutDialog() {

        //暂时先做个简单的弹窗，后续再做界面优化。
        MaterialDialog.Builder materialDialogBuilder =  //
                new MaterialDialog.Builder(mActivityInstance)//该弹窗的上下文对象
                        .title(R.string.surelogoutaccount)//
                        .titleGravity(GravityEnum.CENTER)//
                        .customView(R.layout.viewaccountlogout, false)//
                        .canceledOnTouchOutside(true)
                        .cancelable(true);//某东点击外侧不让消失//
        //展示dialog
        materialDialogLogOut = materialDialogBuilder.show();
        materialDialogLogOut.getTitleView().setTextSize(17);

        //获取布局内的数据
        View viewInSide = materialDialogLogOut.getCustomView();

        //查找view
        //手机号内容,用户名内容；
        TextView textViewPhoneNumberInLogout = (TextView) viewInSide.findViewById(R.id.textviewphonenumberinlogout);

        //确认注销按钮
        RoundTextView btn_account_logout = (RoundTextView) viewInSide.findViewById(R.id.btn_account_logout);

        //再考虑考虑按钮
        TextView textViewThinking = (TextView) viewInSide.findViewById(R.id.textviewthinking);

        //直接填充 现在登录着的用户名。
        if (mSession != null) {
            //暂时用登录名
            textViewPhoneNumberInLogout.setText(mSession.getLoginName());
        }

        //直接注销的 按钮调用就接口
        btn_account_logout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put(Parameterkey.uuid, mSession.getUuid());
                hashMap.put(Parameterkey.verificationCode, Parameterkey.verificationCodeValue);

                AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
                addLogUpLoadInfo.setActivity(mActivityInstance);
                addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPLOAD_LOGOUT_ACCOUNT);//请求数字标识
                addLogUpLoadInfo.setUrlPath(ApiService.cancelCustomerUrl);//url地址
                addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
                addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
                addLogUpLoadInfo.setHashMapParameter(hashMap);

                NetworkManager.getInstance().initRetrofitRxJava()
                        .create(ApiService.class)
                        .cancelCustomer(RequestBody.create(JSON.toJSONString(hashMap, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),//
                                MediaType.parse(ApiService.HEADER_JSON)))//
                        .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                        .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>(ConstantApi.IS_ACTIVITY_ITSELF, SettingActivity.this) {

                            @Override
                            public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                                super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                                //直接提示
                                CommUtils.errorAlertViewFullAll(mActivityInstance, Integer.parseInt(serverCode), serverMessage);
                            }

                        })).flatMap(new Function<String, ObservableSource<Long>>() {

                            @Override
                            public ObservableSource<Long> apply(String s) throws Throwable {

//                                LogUtils.d(ConstantApi.LOGCAT_NOMAL + "注销账号 开始转换");
//                                {
//                                        "code":"20000",
//                                        "data":1,
//                                        "message":"success"
//                                }

                                //------------------------------------------------------------------------------------------------
                                //提示 注销账户成功,直接给弹窗提示--逻辑 走到这里就已经成功了。
                                CommUtils.checkDialog(mAlertView);
                                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.logoutaccountsuccess), true);
                                mAlertView.show();
                                //------------------------------------------------------------------------------------------------

                                return Observable.timer(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread());
                            }
                        })//
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                CommUtils.checkMaterialDialog(materialDialogSubmit);
                                materialDialogSubmit = CommUtils.createMaterialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);
                            }
                        })//
                        .subscribeOn(AndroidSchedulers.mainThread())//
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long longValuePull) throws Exception {

                                //--------------------------------------------------------------------------------
                                //应该是 有 提示？  写在这不论20000或者非20000的都提示；
                                CommUtils.checkMaterialDialog(materialDialogSubmit);
                                CommUtils.checkMaterialDialog(materialDialogLogOut);
                                //--------------------------------------------------------------------------------

                                //直接退出登录,应该是界面刷新到执行退出登录的内容.
                                method_goto_exit_success();

//                                //这里应该是 2秒后,直接跳转逻辑：
//                                mCompositeDisposable.add(Observable.timer(2000, TimeUnit.MILLISECONDS)
//                                        .subscribeOn(AndroidSchedulers.mainThread())//
//                                        .observeOn(AndroidSchedulers.mainThread())//
//                                        .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
//                                        .subscribe(new Consumer<Long>() {
//                                            @Override
//                                            public void accept(Long aLong) throws Exception {
//                                            }
//                                        }));
                            }

                        }, new ErrorConsumer() {
                            @Override
                            protected void error(ApiException e) {

                                //--------------------------------------------------------------------------------
                                CommUtils.checkMaterialDialog(materialDialogSubmit);
                                CommUtils.checkMaterialDialog(materialDialogLogOut);
                                //--------------------------------------------------------------------------------

                            }
                        });

            }
        });

        //再次考虑下
        //再考虑一下
        textViewThinking.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //直接界面弹窗 关闭，什么都不操作。
                if (materialDialogLogOut != null && materialDialogLogOut.isShowing()) {
                    materialDialogLogOut.dismiss();
                    materialDialogLogOut.cancel();
                }

            }
        });

    }

    /**
     * 执行退出登录成功的逻辑
     */
    private void method_goto_exit_success() {

        //这一块貌似完全和20401相同=========================================================
        CommUtils.loginOutClearData(mSession, mSession.getInputNameLastTime());

        //CommUtils.displayToastShort(SettingActivity.this, "退出成功");
        Bundle bundle = new Bundle();
        bundle.putInt(ExtraKey.EXTRA_REQUEST_20401, ExtraValue.RESPONSE_20401);
        //跳转到登录界面去重新登录。
        //这个也要走20401用户信息失效的逻辑
        ActivityUtils.startActivity(bundle, LoginCarActivity.class);

    }


    //检查用户 员工是否开通法大大
//    private void gainCheckPermissions() {
//
//        if (NetworkUtils.isConnected()) {
//
//            HashMap<String, Object> map = new HashMap<>();
//            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//
//            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
//            addLogUpLoadInfo.setActivity(mActivityInstance);
//            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_CHECKOPENFASC_URL);//请求数字标识
//            addLogUpLoadInfo.setUrlPath(ApiService.checkOpenFasc_url);//url地址
//            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
//            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
//            addLogUpLoadInfo.setHashMapParameter(map);
//
//            NetworkManager.getInstance().initRetrofitRxJava()
//                    .create(ApiService.class)
//                    .checkOpenFasc(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
//                            MediaType.parse(ApiService.HEADER_JSON)))
//                    .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
//                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<Boolean>() {
//                        @Override
//                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
//                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
//
//                            //{"data":"","message":"无更多数据","code":"29999"}
//
//                            //这里要不要给提示？无更多数据
//                            if (!TextUtils.isEmpty(serverMessage)) {
//                                ToastUtils.showShort(serverMessage);
//                            }
//
//                        }
//                    })).doOnSubscribe(new Consumer<Disposable>() {
//                        @Override
//                        public void accept(Disposable disposable) throws Throwable {
//                            //
//                        }
//                    }).subscribe(new Consumer<Boolean>() {
//                        @Override
//                        public void accept(Boolean booleanValue) throws Throwable {
//
//                            //设置是否有开通法大大的电子签章能力
////                            {
////                                    "code": "20000",
////                                    "data": true, //true：已开通；false：未开通
////                                    "message": "success"
////                            }
//
//                            if (booleanValue) {
//                                //已开通电子签章能力；
//                                //gainDatas();
//                                //ToastUtils.showShort("已开通电子签章认证~");
//                                CommUtils.checkDialog(mAlertView);
//                                mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.open_signature_has_link), true);
//                                mAlertView.show();
//
//                            } else {
//
//                                //如果未开通法大大企业认证，那么弹窗介绍企业认证图文介绍， 认证 电子签章
//                                //立即调用 打开企业认证的接口
//                                gain_check_permissions_open_signature();
//
//                            }
//
//                        }
//                    }, new ErrorConsumer() {
//
//                        @Override
//                        protected void error(ApiException apiException) {
//
//                            //页面报错；给提示
//                            if (apiException != null) {
//                                ToastUtils.showShort(apiException.getDisplayMessage());
//                            }
//
//                        }
//                    });
//
//        } else {
//
//            ToastUtils.showShort(StringUtils.getString(R.string.http_exception_network));
//
//        }
//
//    }

    //打开电子签章的认证链接，然后跳转到webView
    private void gain_check_permissions_open_signature() {

        HashMap<String, Object> map = new HashMap<>();

        map.put(Parameterkey.shopId, mSession.getShopInfoId());
//        map.put(Parameterkey.companyId, mSession.getCompanyId());
//        map.put(Parameterkey.pagination, pagination_upLoad);//
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_OPENFASCFOREMPLOYEE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.openFascForEmployee_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .openFascForEmployee(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(SettingActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //弹出打开链接的
                        if (!TextUtils.isEmpty(stringValue)) {

                            //跳转到外部浏览器：不可行，放弃；
                            //需要打开到APP内部的webView才可以；
                            method_check_permissions_dialog(stringValue);

                        } else {
                            //直接提示？
                            ToastUtils.showShort(R.string.open_links_is_null);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                        //页面报错；
                        if (apiException != null) {
                            ToastUtils.showShort(apiException.getDisplayMessage());
                        }

                    }
                });

    }


    private MaterialDialog materialDialogCustomView;

    //检查用户所在企业，是否开通过 法大大，该弹窗是没有认证过，就弹窗提示；
    private void method_check_permissions_dialog(String _contentResult) {

        //弹窗布局
//        View viewCard = View.inflate(mActivityInstance, R.layout.signaturepanel, null);
        View viewCard = View.inflate(mActivityInstance, R.layout.signaturepanel_person, null);

        if (viewCard != null) {

            //标题 卡券的
            TextView textViewQrName = (TextView) viewCard.findViewById(R.id.textviewqrnameperson);
            //填充房间号的名称内容
//            textViewQrName.setText(_siteNo);

            //图片的内容  imageviewpaintbookingqrcode
            ImageView imageViewQRCode = (ImageView) viewCard.findViewById(R.id.imageviewpaintbookingqrcodeperson);
            //关闭 按钮
            RoundTextView textViewCardCancel = (RoundTextView) viewCard.findViewById(R.id.textviewsignaturecancelperson);
            //保存为图片的按钮
            RoundTextView textViewCardSure = (RoundTextView) viewCard.findViewById(R.id.textviewtosignatureperson);


            //一个图文的介绍 等，内容还不确定；
//            String imagePath = PathUtils.getExternalAppFilesPath() + File.separator + ConstantSign.DOWNAPP + File.separator + ConstantSign.IMG + TimeUtils.getNowString() + ConstantSign.IMG_POSTFIX;
//            FileUtils.createOrExistsFile(imagePath);
//
//            boolean resultValue = DemoImage.base64ToImage(_imageUrlBase64, imagePath);
//            //boolean resultValue = DemoImage.base64ToImage(_imageUrlBase64, PathUtils.getExternalAppFilesPath() + File.separator + ConstantSign.IMG + TimeUtils.getNowString() + ConstantSign.IMG_POSTFIX);
//
//            if (resultValue) {
//
//                Glide.with(SignatureActivity.this)
//                        .load(imagePath)
//                        .placeholder(R.drawable.icon_errorfang)//
//                        .error(R.drawable.icon_errorfang)//
//                        .fitCenter()
//                        .diskCacheStrategy(DiskCacheStrategy.NONE)//动态获取新值不缓存
////                        .override(120, 60)
//                        .into(imageViewQRCode);
//
//                //PathUtils.getExternalAppFilesPath() + File.separator + ConstantSign.IMG + TimeUtils.getNowString() + ConstantSign.IMG_POSTFIX
//
////                点击查看大图
//                imageViewQRCode.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
//                    @Override
//                    public void onDebouncingClick(View v) {
//                        //验证码的查看大图
//                        new XPopup.Builder(SignatureActivity.this)
//                                .asImageViewer(imageViewQRCode, //
//                                        imagePath,//
//                                        new SmartGlideImageLoader())//
//                                .show();
//                    }
//                });


            if (textViewCardCancel != null) {
                textViewCardCancel.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                    @Override
                    public void onDebouncingClick(View v) {

                        //此时 弹窗是已经被弹出的
                        if (materialDialogCustomView != null) {
                            materialDialogCustomView.dismiss();
                        }

                        //直接关闭该页面整体的,因为不认证是没法儿用的。
                        methodBack();

                    }
                });
            }


            if (textViewCardSure != null) {

                textViewCardSure.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                    @Override
                    public void onDebouncingClick(View v) {

                        //打开浏览器的逻辑，是不可行的，放弃；因为交互信息 后台无法给到手机端
                        //CommUtils.linkJumpDialogSignature(SignatureActivity.this, SignatureActivity.this, _contentResult);

                        //应该是打开内部的webView才可以；可以实现法大大给认证结果给H5，下一步Android和H5交互,这样手机端才知道认证成功；
                        ViewUitls.method_toWebView_signature(getString(R.string.title_dialog_signature), _contentResult);

                        //获取权限
//                        if (!AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)
//                                || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {
//
//                            CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
//                                @Override
//                                public void doSomeThing() {
//
//                                    //添加访问权限内容
//                                    AndPermission.with(SignatureActivity.this)
//                                            .runtime()//
//                                            .permission(Permission.READ_EXTERNAL_STORAGE, //
//                                                    Permission.WRITE_EXTERNAL_STORAGE)//
//                                            .rationale(new RuntimeRationale())//
//                                            .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
//                                                @Override
//                                                public void onAction(List<String> permissions) {
//
//
//
//                                                }
//                                            }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
//                                                @Override
//                                                public void onAction(List<String> permissions) {
//
//                                                    ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);
//
//                                                    PermissionSetting permissionSetting = new PermissionSetting(mActivityInstance);
//
//                                                    if (AndPermission.hasAlwaysDeniedPermission(SignatureActivity.this, permissions)) {
//                                                        permissionSetting.showSetting(ConstantApi.PERMISSION_NORMAL, SignatureActivity.this, permissions);
//                                                    }
//
//                                                }
//                                            }).start();
//
//                                }
//                            });
//
//                        } else {
//
////                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "正常的权限已经打开，可以执行拍照操作");
////                            methodOpenImage(imagePath);
//
//                        }


                    }
                });
            }

            //激发 弹窗弹出内容
            materialDialogCustomView = new MaterialDialog.Builder(SettingActivity.this)
                    .customView(viewCard, false)
                    .contentColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                    //.positiveText("确定")
                    .positiveColor(ColorUtils.getColor(R.color.dark))
                    //.negativeText("取消")
                    .canceledOnTouchOutside(false)
                    .show();


        }


    }

}
